package cn.topevery.garden.framework.util;

import org.apache.commons.lang3.StringUtils;

import java.time.Duration;
import java.time.LocalDateTime;

public class DateTimeUtil {
    public DateTimeUtil() {
    }

    public static String lastSecondOfDay(String day) {
        String result = day;
        if (StringUtils.isNotEmpty(day) && day.length() == 10) {
            result = day + " 23:59:59";
        }

        return result;
    }

    public static String secondToTime(Integer seconds) {
        if (seconds == null) {
            seconds = 0;
        }

        if (seconds <= 60) {
            return seconds + "秒";
        } else {
            long days = (long) (seconds / 86400);
            seconds = seconds % 86400;
            long hours = (long) (seconds / 3600);
            seconds = seconds % 3600;
            long minutes = (long) (seconds / 60);
            seconds = seconds % 60;
            if (days > 0L) {
                return days + "天" + hours + "小时" + minutes + "分" + seconds + "秒";
            } else {
                return hours > 0L ? hours + "小时" + minutes + "分" + seconds + "秒" : minutes + "分" + seconds + "秒";
            }
        }
    }

    public static String GetTimeSpan(LocalDateTime beginDate, LocalDateTime endDate) {
        if (beginDate == null || endDate == null) {
            return "";
        }
        String result = "";
        Duration duration = Duration.between(beginDate, endDate);
        if (duration.toDays() > 0) {
            result = String.format("%s天%s小时%s分%s秒", duration.toDays(), duration.toHours(), duration.toMinutes(), duration.toMillis() * 1000);

        } else if (duration.toHours() > 0) {
            result = String.format("%s小时%s分%s秒", duration.toHours(), duration.toMinutes(), duration.toMillis() * 1000);

        } else if (duration.toMinutes() > 0) {
            result = String.format("%s分%s秒", duration.toMinutes(), duration.toMillis() * 1000);
        } else if (duration.toMillis() < 0) {
            result = "0秒";

        } else {
            result = String.format("%s秒", duration.toMillis() * 1000);
        }
        return result;

    }

    public static String GetTimeString(int seconds) {
        String ret = seconds >= 0 ? "" : "-";

        seconds = Math.abs(seconds);
        if (seconds != 0) {
            int tmp;
            int days = seconds / (24 * 60 * 60);

            tmp = (seconds - days * 24 * 60 * 60);

            int hh = tmp / (60 * 60);
            tmp = tmp - hh * 60 * 60;

            int min = tmp / 60;

            tmp = tmp - min * 60;
            if (days > 0) {
                ret = ret + days + "天";
            }
            if (hh > 0) {
                ret = ret + hh + "小时";
            }
            if (min > 0) {
                ret = ret + min + "分";
            }
            if (tmp > 0) {
                ret = ret + tmp + "秒";
            }
        } else {
            ret = "0";
        }
        return ret;
    }
}
